package com.longlong.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.longlong.bean.AccessTokenGzhBean;
import com.longlong.config.AccessTokenGzhConfig;
import com.longlong.service.AccessTokenGzhService;
import com.longlong.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class AccessTokenGzhServiceImpl implements AccessTokenGzhService {
    @Autowired
    private AccessTokenGzhConfig accessTokenGzhConfig;

    /*
    * access token 对象
    * */
    private AccessTokenGzhBean accessTokenGzhBean;

    private static final String Url = "https://api.weixin.qq.com/cgi-bin/token";

    @Override
    public void refreshAccessToken(String appid,String appSecret) throws IOException {
        String result = HttpClientUtils.get(Url, AccessTokenGzhBean.requestOf(appid, appSecret));
        //3.对微信返回的数据进行转换
        JSONObject jsonObject = JSONObject.parseObject(result);
        Long expires_in = jsonObject.getLong("expires_in");
        String access_token = jsonObject.getString("access_token");
        accessTokenGzhBean = AccessTokenGzhBean.responseOf(access_token,expires_in);
    }

    @Override
    public String getAccessToken() throws IOException {
        if(accessTokenGzhBean == null||accessTokenGzhBean.isExpired()){
            refreshAccessToken(accessTokenGzhConfig.WX_OPEN_APP_ID,accessTokenGzhConfig.WX_OPEN_APP_SECRET);
        }
        return accessTokenGzhBean.getAccessToken();
    }



}
